import {
  cancel,
  intro,
  isCancel,
  outro,
  select,
  text,
  spinner,
  confirm,
} from "@clack/prompts";
import { type OptionValues } from "commander";
import Log from "@/utils/log";
import getLanguage from "@/utils/getLanguage";
import { fileURLToPath } from "url";
import path from "path";
import renderTemplate from "@/utils/renderTemplate";
import * as banners from "@/utils/banner";
import { red } from "picocolors";
import getPackageManager from "@/utils/npm-type";

const lang = getLanguage();
const installCommand = getPackageManager();

async function unwrapPrompt<T>(
  maybeCancelPromise: Promise<T | symbol>
): Promise<T> {
  const result = await maybeCancelPromise;
  if (isCancel(result)) {
    cancel(red("✖") + ` ${lang.errors.operationCancelled}`);
    process.exit(0);
  }
  return result;
}

// 根据需求创建模版项目
export default async function create(args: OptionValues) {
  const templateRoot = fileURLToPath(new URL("./template", import.meta.url));
  // 打印banner
  intro(
    process.stdout.isTTY && process.stdout.getColorDepth() > 8
      ? banners.gradientBanner
      : banners.defaultBanner
  );

  // 项目名称
  let projectName = args.name;
  if (!projectName) {
    projectName = await unwrapPrompt(
      text({
        message: lang.create.input.projectName,
        placeholder: lang.create.input.placeholderProjectName,
      })
    );
  }

  // 框架类型
  const root = path.join(process.cwd(), projectName);
  function render(templateName: string) {
    const templateDir = path.resolve(templateRoot, templateName);
    renderTemplate(templateDir, root);
  }
  let template = args.template;
  if (!template) {
    const templateList = [
      {
        name: "Vue",
        value: "vue",
      },
      {
        name: "React",
        value: "react",
      },
    ];
    template = await unwrapPrompt(
      select({
        message: lang.create.input.template,
        options: templateList,
      })
    );
    console.log(template);
  }

  // vue模版项目，判断是什么项目就创建什么项目
  if (template.toLowerCase() === "vue") {
    render("base/Vue");
  } else if (template.toLowerCase() === "react") {
    render("base/React");
  }
  // 安装依赖 
  const s = spinner();
  const isInstall = await unwrapPrompt(
    confirm({
      message: lang.create.input.installDependencies,
    })
  );
  if (isInstall) {
    s.start(lang.create.input.installingDependencies);
    try {
      const { execSync } = await import("child_process");
      execSync(`${installCommand} install`, {
        cwd: root,
        stdio: "inherit",
      });
    } catch (e) {
      const error = e as Error & {
        status?: number;
        code?: string;
        signal?: string;
      };
      if (error.status) {
        Log.error(`子进程退出码: ${error.status}`);
      }
      if (error.signal) {
        Log.error(`终止信号: ${error.signal}`);
      }
      process.exit(1);
    }
    s.stop(lang.create.input.installDependenciesSuccess);
  }
  let outroMessage = `\n${lang.create.success}`;
  outro(outroMessage);
}
